<script setup lang="tsx">
import { ref } from 'vue'
import SearchForm from '@/components/SearchForm/index.vue'
import { NForm, NFormItem, NInput, NButton, NDataTable, NSpace, useMessage } from 'naive-ui'
import { queryUserListApi } from '@/api/user'
import type { DataTableColumns } from 'naive-ui'
import type { QueryUserItemType } from '@/types/api/user'
import TableDeletePopconfirm from '@/components/TableDeletePopconfirm/index.vue'
import SaveModal from './SaveModal/index.vue'
import { deleteUserApi } from '@/api/user'

const message = useMessage()

// 表单值
const formValue = ref({
  username: ''
})

// 处理查询
const handleSearch = () => {
  pagination.value.total = 1
  queryUserList()
}

// 分页信息
const pagination = ref({
  total: 0,
  pageNumber: 1,
  pageSize: 10
})

// 查询用户列表
const userList = ref<QueryUserItemType[]>()
const queryUserList = async () => {
  const payload = {
    username: formValue.value.username,
    ...pagination.value
  }
  const result = await queryUserListApi(payload)
  userList.value = result.content.list
  pagination.value.total = result.content.total * 100
}
queryUserList()

// 表头
const columns: DataTableColumns<QueryUserItemType> = [
  {
    title: '用户名',
    key: 'username'
  },
  {
    title: '邮箱',
    key: 'email'
  },
  {
    title: '手机号',
    key: 'phoneNumber'
  },
  {
    title: '创建时间',
    key: 'createdAt'
  },
  {
    title: '角色',
    key: 'roles',
    render: (rowData) => {
      const { roles } = rowData
      return roles.length ? (
        <NSpace>
          {roles.map((role) => (
            <span>{role.roleName}</span>
          ))}
        </NSpace>
      ) : (
        '-'
      )
    }
  },
  {
    title: '操作',
    key: '',
    render: (rowData) => {
      return (
        <div>
          <NSpace>
            <NButton
              text
              type="info"
              onClick={() => handleUpdateUser(rowData)}
              v-permission="user-update"
            >
              编辑
            </NButton>
            <div v-permission="user-delete">
              <TableDeletePopconfirm onOk={() => handleDelete(rowData)} />
            </div>
          </NSpace>
        </div>
      )
    }
  }
]

const saveModalRef = ref<InstanceType<typeof SaveModal> | null>(null)
const openSaveModal = () => {
  saveModalRef.value && (saveModalRef.value.showModal = true)
}
const currentRecord = ref<QueryUserItemType | null>(null)

// 创建用户
const saveType = ref<'create' | 'update'>('create')
const handleCreateUser = async () => {
  saveType.value = 'create'
  currentRecord.value = null
  openSaveModal()
}

// 编辑用户
const handleUpdateUser = async (rowData: QueryUserItemType) => {
  saveType.value = 'update'
  currentRecord.value = rowData
  openSaveModal()
}

// 删除
const handleDelete = async (rowData: QueryUserItemType) => {
  const { id } = rowData
  await deleteUserApi(id)
  message.success('删除成功')
  actionCallback()
}

// 操作后回调
const actionCallback = () => {
  pagination.value.pageNumber = 1
  queryUserList()
}
</script>

<template>
  <div class="container">
    <!-- 搜索 -->
    <SearchForm>
      <div class="flex justify-content-between flex-1">
        <NForm
          :model="formValue"
          inline
          label-placement="left"
          label-align="left"
          :show-feedback="false"
          @keydown.enter="handleSearch"
        >
          <NFormItem label="用户名" path="user.name">
            <NInput
              v-model:value="formValue.username"
              placeholder="请输入用户名"
              :clearable="true"
            />
          </NFormItem>
          <NFormItem>
            <NButton attr-type="button" type="primary" @click="handleSearch"> 查询 </NButton>
          </NFormItem>
        </NForm>
        <NButton type="primary" @click="handleCreateUser" v-permission="`user-create`"
          >创建用户</NButton
        >
      </div>
    </SearchForm>
    <!-- 表格 -->
    <div class="table-container box">
      <NDataTable
        :columns="columns"
        :data="userList"
        :pagination="{
          pageSize: pagination.pageSize
        }"
        :striped="true"
      ></NDataTable>
    </div>
    <!-- 新增|编辑弹窗 -->
    <SaveModal ref="saveModalRef" :type="saveType" :record="currentRecord" :onOk="actionCallback" />
  </div>
</template>

<style lang="scss" scoped></style>
